import React, { useState, useMemo } from 'react';
import { FolderOpenOutlined, FolderOutlined } from '@ant-design/icons';
import { TextMethodType } from "../../../common/MethodType";
import { observer } from "mobx-react";
import { Axios } from "tiklab-core-ui";
import { Tree } from "antd";

/**
 * 分享页中 目录导航
 */
const NodeTreeShare = (props) => {
    const { setApiData, setWsData, setNodeType, treeList } = props;
    const [expandedKeys, setExpandedKeys] = useState([]);
    const [selectedKeys, setSelectedKeys] = useState([]);

    // 定义节点样式
    const nodeStyles = useMemo(() => ({
        nodeTitle: {
            display: 'flex',
            alignItems: 'center',
            // padding: '4px 0',
            cursor: 'pointer',
            borderRadius: '3px',
            transition: 'all 0.2s',
            width: '100%',
        },
        iconContainer: {
            marginRight: '4px',
            display: 'flex',
            alignItems: 'center',
        },
        textContainer: {
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
        },
        methodBadge: {
            padding: '2px 6px',
            borderRadius: '3px',
            fontSize: '12px',
            fontWeight: '500',
        }
    }), []);

    /**
     * 处理节点点击事件
     * @param {Object} item - 节点数据
     */
    const handleNodeClick = async (item) => {
        // 设置选中的节点
        setSelectedKeys([item.id]);

        switch (item.type) {
            case 'category':
                // 点击目录展开收缩
                const key = item.id;
                const nextExpandedKeys = expandedKeys.includes(key)
                    ? expandedKeys.filter(k => k !== key)
                    : [...expandedKeys, key];
                setExpandedKeys(nextExpandedKeys);
                break;
            case "http":
                setNodeType(item.type);
                const param = new FormData();
                param.append("id", item.id);
                const res = await Axios.post(`/share/findHttpApi`, param);
                setApiData(res.data);
                break;
            case "ws":
                setNodeType(item.type);
                const wsParam = new FormData();
                wsParam.append("id", item.id);
                const wsInfo = await Axios.post(`/share/findWSApi`, wsParam);
                setWsData(wsInfo.data);
                break;
            default:
                break;
        }
    };

    /**
     * 获取节点图标
     * @param {string} type - 节点类型
     * @param {string} methodType - HTTP方法类型
     * @returns {JSX.Element} 图标元素
     */
    const getNodeIcon = (type, methodType) => {
        if (type === 'category') {
            return null; // 分类的图标由Tree.TreeNode的icon属性提供
        } else if (type === 'ws') {
            return (
                <span
                    style={{
                        color: "#0070ff",
                        backgroundColor: 'rgba(0, 112, 255, 0.1)',
                        ...nodeStyles.methodBadge
                    }}
                >
                    WS
                </span>
            );
        } else if (type === 'http') {
            return <TextMethodType type={methodType} />;
        }
        return null;
    };

    /**
     * 递归渲染树节点
     * @param {Array} data - 节点数据
     * @returns {Array} 树节点元素
     */
    const renderTreeNodes = (data) => {
        return data?.map((item) => {
            // 通用节点标题渲染
            const title = (
                <div
                    style={nodeStyles.nodeTitle}
                    onClick={() => handleNodeClick(item)}
                >
                    <span style={nodeStyles.iconContainer}>
                        {getNodeIcon(item.type, item.methodType)}
                    </span>
                    <span style={nodeStyles.textContainer}>
                        {item.name}
                    </span>
                </div>
            );

            // 分类节点
            if (item.children && item.children.length > 0) {
                return (
                    <Tree.TreeNode
                        key={item.id}
                        title={title}
                        icon={({ expanded }) => expanded ? <FolderOpenOutlined /> : <FolderOutlined />}
                        dataRef={item}
                    >
                        {renderTreeNodes(item.children)}
                    </Tree.TreeNode>
                );
            }

            // 叶子节点
            return (
                <Tree.TreeNode
                    key={item.id}
                    title={title}
                    icon={item.type === 'category' ? <FolderOutlined /> : null}
                    dataRef={item}
                />
            );
        });
    };

    /**
     * 处理选中节点事件
     * @param {Array} selectedKeys - 选中的节点key数组
     * @param {Object} info - 事件信息对象
     */
    const handleSelect = (selectedKeys, info) => {
        setSelectedKeys(selectedKeys);
    };

    return (
        <Tree
            showIcon
            expandedKeys={expandedKeys}
            onExpand={setExpandedKeys}
            selectedKeys={selectedKeys}
            onSelect={handleSelect}
            defaultExpandAll={true}
        >
            {renderTreeNodes(treeList)}
        </Tree>
    );
};

export default observer(NodeTreeShare);